package com.atguigu.edu.controller;

import com.atguigu.edu.bean.UserChangeCtPerType;
import com.atguigu.edu.bean.UserPageCt;
import com.atguigu.edu.service.UserStatsService;
import com.atguigu.edu.util.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class UserStatsController {
    @Autowired
    private UserStatsService userStatsService;

    @RequestMapping("/userct")
    public String getUserCt(@RequestParam(value = "date",defaultValue = "0")Integer date){
        if(date==0){
            date = DateFormatUtil.now();
        }
        List<UserChangeCtPerType> userChangeCtPerTypeList = userStatsService.getUserCt(date);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{\"status\": 0,\n" +
                "\"data\": {\"columns\": [{\"name\": \"变动类型\",\"id\": \"type\"},{\"name\": \"用户数\",\"id\": \"user_ammount\"}],\n" +
                "\t\t \"rows\": [");
        for (int i = 0; i < userChangeCtPerTypeList.size(); i++) {
            UserChangeCtPerType userChangeCtPerType = userChangeCtPerTypeList.get(i);
            String type = userChangeCtPerType.getType();
            Integer userCt = userChangeCtPerType.getUserCt();
            stringBuilder.append("{\"type\": \""+type+"\",\"user_ammount\": "+userCt+"}");
            if(i<userChangeCtPerTypeList.size()-1){
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]}}");
        String jsonStr = stringBuilder.toString();
        return jsonStr;
    }
    @RequestMapping("/useranalyze")
    public String getUserAnalyze(@RequestParam(value = "date",defaultValue = "0")Integer date){
        if(date==0){
            date = DateFormatUtil.now();
        }
        StringBuilder stringBuilder = new StringBuilder("{\"status\": 0,\n" +
                " \"data\": [");
        List<UserPageCt> userPageCtList = userStatsService.getUserAnalyze(date);
        for (int i = 0; i < userPageCtList.size(); i++) {
            UserPageCt userPageCt = userPageCtList.get(i);
            String pageId = userPageCt.getPageId();
            Integer uvCt = userPageCt.getUvCt();
            stringBuilder.append("{\"name\": \""+pageId+"\",\"value\": "+uvCt+"}");
            if(i<userPageCtList.size()-1){
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("]}");
        String jsonStr = stringBuilder.toString();
        return jsonStr;
    }

}
